package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.entity.Book;
import com.bookmanger.entity.Order;
import com.bookmanger.entity.dto.BookBorrowCountDTO;
import com.bookmanger.entity.dto.OrderRankDTO;
import com.bookmanger.entity.vo.BookCategoryCountVO;
import com.bookmanger.mapper.OrderMapper;
import com.bookmanger.service.BookService;
import com.bookmanger.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huangfuhao
 * @Date 2024/10/26
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private BookService bookService;
    /**
     * 获取借阅排行榜
     *
     * @return
     */
    @Override
    public Result<List<OrderRankDTO>> getOrderRank() {
        //查询借阅排行榜
        List<BookBorrowCountDTO> topBorrowedBooks = this.baseMapper.getTopBorrowedBooks();
        List<Long> idList = topBorrowedBooks.stream().map(BookBorrowCountDTO::getBookId).toList();
        //根据orderRankDTOS中的bookId查询对应的书籍信息
        Map<Long, Book> collect = bookService.getBaseMapper().selectBatchIds(idList).stream().collect(Collectors.toMap(
                Book::getId,
                book -> book
        ));
        List<OrderRankDTO> orderRankDTOS=new ArrayList<>();
        for (int i = 0; i < topBorrowedBooks.size(); i++) {
            Book book = collect.get(topBorrowedBooks.get(i).getBookId());
            OrderRankDTO orderRankDTO = BeanUtil.copyProperties(book, OrderRankDTO.class);
            orderRankDTO.setBookId(book.getId());
            orderRankDTO.setId((long) (i+1));
            orderRankDTO.setBorrowCount(topBorrowedBooks.get(i).getBorrowCount());
            orderRankDTOS.add(orderRankDTO);
        }
        return Result.success(orderRankDTOS);
    }

    @Override
    public Result<Integer> getOrderCount() {
        Integer orderCount = Math.toIntExact(baseMapper.selectCount(null));
        return Result.success(orderCount);
    }

    @Override
    public Result<Integer> getOrderCountNullHandle() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        // status = 0 或 status = 2
        queryWrapper.eq("status", 0).or().eq("status", 2);
        Integer orderCount = Math.toIntExact(baseMapper.selectCount(queryWrapper));
        return Result.success(orderCount);
    }

    @Override
    public Result<List<BookCategoryCountVO>> getOrderBookCategoryCount() {
        return Result.success(baseMapper.getOrderBookCategoryCount());
    }
}
